package com.hmdp.service.impl;

import cn.hutool.Hutool;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private com.hmdp.propercies.jwtProperties jwtProperties;

    @Override
    public Result sendCode(String phone) {
          //验证手机号是否合法
        if(RegexUtils.isPhoneInvalid(phone)){
             return Result.fail("手机号格式有误");
        }
        String code = RandomUtil.create();
        stringRedisTemplate.opsForValue().set(phone,code,60, TimeUnit.SECONDS);
        log.info("验证码为：{}",code);
        return Result.ok();

    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        User SelectUser = new User();
        BeanUtils.copyProperties(loginForm,SelectUser);
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
        String password = loginForm.getPassword();
        User user = userMapper.Select(SelectUser);
        //如果该用户不存在
        if(password != null){
              if(user == null){
                   return Result.fail("账号或密码错误");
              }
              //生成token
            Map<String,Object> map = new HashMap<>();
              map.put("userId",user.getId());
              String token =  JwtUtil.createJWT(jwtProperties.getSecretkey(),jwtProperties.getTtl(),map);
              ThroadLocal.set(user.getId());
              return Result.ok(ThroadLocal.get());

        }
        else{
            if(user == null){
                 //该用户不存在，应直接注册新账号
                 if(!stringRedisTemplate.opsForValue().get(phone).equals(code)){
                      return Result.fail("验证码错误");
                 }
                 else{
                     SelectUser.setCreateTime(LocalDateTime.now());
                     SelectUser.setUpdateTime(LocalDateTime.now());
                     userMapper.Save(SelectUser);
                     //生成token
                     Map<String,Object> map = new HashMap<>();
                     map.put("userId",SelectUser.getId());

                     String token =  JwtUtil.createJWT(jwtProperties.getSecretkey(),jwtProperties.getTtl(),map);
                     ThroadLocal.set(SelectUser.getId());
                     return Result.ok(ThroadLocal.get());
                 }
            }
            else{
                if(!stringRedisTemplate.opsForValue().get(phone).equals(code)){
                    return Result.fail("验证码错误");
                }
                else{
                    //生成token
                    Map<String,Object> map = new HashMap<>();
                    map.put("userId",user.getId());
                    String token =  JwtUtil.createJWT(jwtProperties.getSecretkey(),jwtProperties.getTtl(),map);
                    ThroadLocal.set(user.getId());
                    return Result.ok(ThroadLocal.get());
                }
            }
        }



    }

    @Override
    public User me() {
          User user = new User();
          user.setId(ThroadLocal.get());

          return userMapper.Select(user);
    }
}
